import socket
from threading import Thread
import pickle
from position import *
import time

# global p, v


def run(event,gp, gv):
    # global p, v
    server_addr = ('192.168.3.5', 7788)
    client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client_socket.connect(server_addr)
    first = True
    while True:
        try:
            recv_data = client_socket.recv(84)
            if len(recv_data)!=84:
                print(f'len of data is wrong: {len(recv_data)}')
                continue
                
            data=np.frombuffer(recv_data, dtype='float16').reshape(14,3)
            for i in range(7):
                gp[i]=pose(data[i][0], data[i][1], data[i][2])
                gv[i]=pose(data[i+7][0], data[i+7][1])
            if first:
                event.set()
                first = False
        except socket.error as e:
            print(e)
            break
        except Exception as e:
            print(e, len(recv_data))


def client_get():
    global p, v
    server_addr = ('192.168.3.5', 7788)
    client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client_socket.connect(server_addr)
    first = True
    ct=0
    cf=0
    ts=0
    count=0
    while True:
        try:
            t1=time.time()
            recv_data = client_socket.recv(84)
            # print(len(recv_data))
            data=np.frombuffer(recv_data, dtype='float16').reshape(14,3)
            # p = pickle.loads(recv_data)[0]
            # v = pickle.loads(recv_data)[1]
            # p = poses(pickle.loads(recv_data))        # v = pickle.loads(recv_data[1])
            if first:
                first = False
            print(data[0][0])
            ct+=1
            # print(f'true count={ct}')
        except Exception as e:
            cf+=1
            # print(f'false count={cf}')
            print(e)
        finally:
            t2=time.time()
            count+=1
            ts+=t2-t1
            print(f'count:{count}, avg time gap is {ts/count}')


if __name__ == "__main__":
    client_get()
